package com.xmtlxx.web.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.xmtlxx.common.annotation.Log;
import com.xmtlxx.common.annotation.RepeatSubmit;
import com.xmtlxx.common.constant.UserConstants;
import com.xmtlxx.common.core.controller.BaseController;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.domain.entity.SysRole;
import com.xmtlxx.common.core.domain.entity.SysTenant;
import com.xmtlxx.common.core.domain.entity.SysUser;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.core.validate.AddGroup;
import com.xmtlxx.common.core.validate.EditGroup;
import com.xmtlxx.common.core.validate.QueryGroup;
import com.xmtlxx.common.enums.BusinessType;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.common.utils.poi.ExcelUtil;
import com.xmtlxx.system.domain.vo.SysTenantVo;
import com.xmtlxx.system.service.ISysRoleService;
import com.xmtlxx.system.service.ISysTenantService;
import com.xmtlxx.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 租户Controller
 *
 * @author xmtlxx
 * @date 2022-04-17
 */
@Validated
@Api(value = "租户控制器", tags = {"租户管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/tenant")
public class SysTenantController extends BaseController {

    private final ISysTenantService iSysTenantService;

    private final ISysUserService userService;

    private final ISysRoleService roleService;

    /**
     * 返回一个初始化的对象到前端，方便进行动态渲染
     */
    @ApiOperation("用于返回一个初始化对象")
    @PostMapping("/initBean")
    R<Map<String, Object>> initBean(){
        SysTenantVo vo = new SysTenantVo();
        //可以对数据进行初始化
        Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return R.ok(ajax);
    }

    /**
     * 查询租户列表
     */
    @ApiOperation("查询租户列表")
    @SaCheckPermission("system:tenant:list")
    @GetMapping("/list")
    public TableDataInfo<SysTenant> list(@Validated(QueryGroup.class) SysTenant bo, PageQuery pageQuery) {
        return iSysTenantService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出租户列表
     */
    @ApiOperation("导出租户列表")
    @SaCheckPermission("system:tenant:export")
    @Log(title = "租户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated SysTenant bo, HttpServletResponse response) {
        List<SysTenant> list = iSysTenantService.queryList(bo);
        ExcelUtil.exportExcel(list, "租户", SysTenant.class, response);
    }

    /**
     * 获取租户详细信息
     */
    @ApiOperation("获取租户详细信息")
    @SaCheckPermission("system:tenant:query")
    @GetMapping("/{tenantId}")
    public R<Map<String, Object>> getInfo(@ApiParam("主键")
                                     @NotNull(message = "主键不能为空")
                                     @PathVariable("tenantId") Long tenantId) {
        SysTenant tenant = iSysTenantService.queryById(tenantId);
        SysUser user = userService.getTenantAdminUser(tenantId);
        SysTenantVo vo = new SysTenantVo();
        BeanUtil.copyProperties(tenant,vo);
        BeanUtil.copyProperties(user,vo);

        Map<String, Object> ajax = new HashMap<>();
        ajax.put("item",vo);
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roleIds", user.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        ajax.put("roles", LoginHelper.isAdmin(user.getUserId()) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));

        return R.ok(ajax);
    }

    /**
     * 新增租户
     */
    @ApiOperation("新增租户")
    @SaCheckPermission("system:tenant:add")
    @Log(title = "租户", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysTenantVo vo) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(vo,user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return R.fail("新增租户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(vo.getPhonenumber())
            && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("新增租户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
            && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("新增租户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(iSysTenantService.insertByBo(vo) ? 1 : 0);
    }

    /**
     * 修改租户
     */
    @ApiOperation("修改租户")
    @SaCheckPermission("system:tenant:edit")
    @Log(title = "租户", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysTenantVo vo) {
        SysUser user = new SysUser();
        BeanUtil.copyProperties(vo,user);
        user.setUserId(userService.getTenantAdminUser(vo.getTenantId()).getUserId());
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
            && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return R.fail("修改租户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
            && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return R.fail("修改租户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        return toAjax(iSysTenantService.updateByBo(vo) ? 1 : 0);
    }

    /**
     * 删除租户
     */
    @ApiOperation("删除租户")
    @SaCheckPermission("system:tenant:remove")
    @Log(title = "租户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{tenantIds}")
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] tenantIds) {
        return toAjax(iSysTenantService.deleteWithValidByIds(Arrays.asList(tenantIds), true) ? 1 : 0);
    }

    /**
     * 查询已分配用户租户列表
     */
    @ApiOperation("查询已分配用户租户列表")
    @SaCheckPermission("system:tenant:list")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo<SysUser> allocatedList(SysUser user, PageQuery pageQuery) {
        return userService.selectAllocatedList(user, pageQuery);
    }

    /**
     * 查询未分配用户租户列表
     */
    @ApiOperation("查询未分配用户租户列表")
    @SaCheckPermission("system:tenant:list")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo<SysUser> unallocatedList(SysUser user, PageQuery pageQuery) {
        return userService.selectUnallocatedList(user, pageQuery);
    }

    /**
     * 取消授权用户
     */
    @ApiOperation("取消授权用户")
    @SaCheckPermission("system:tenant:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public R<Void> cancelAuthUser(@RequestBody SysUser user) {
        return toAjax(iSysTenantService.deleteAuthUser(user));
    }

    /**
     * 批量取消授权用户
     */
    @ApiOperation("批量取消授权用户")
    @SaCheckPermission("system:tenant:edit")
    @Log(title = "租户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public R<Void> cancelAuthUserAll(Long tenantId, Long[] userIds) {
        return toAjax(iSysTenantService.deleteAuthUsers(tenantId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @ApiOperation("批量选择用户授权")
    @SaCheckPermission("system:tenant:edit")
    @Log(title = "租户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public R<Void> selectAuthUserAll(Long tenantId, Long[] userIds) {
        return toAjax(iSysTenantService.insertAuthUsers(tenantId, userIds));
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @SaCheckPermission("system:tenant:edit")
    @Log(title = "租户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R<Void> changeStatus(@RequestBody SysTenant vo) {
        return  toAjax(iSysTenantService.updateStatus(vo));
    }
}
